<?php

namespace App\Http\Middleware\Api\v1;

use Closure;
use App\Models\ApiKey;
use App\Models\ApiKeyRequestLog;
use Illuminate\Support\Facades\Cache;

class ApiKeyRequest
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        if(!empty($response->original['error']))
        {
            return $response;
        }
        $data = json_decode($response->original);
        if($data->code == 200)
        {
            $apikey = ApiKey::where('key', $request->api_key)
                            ->where('secret', $request->api_secret)
                            ->first();
            if (empty($apikey->type)) {
                Cache::put($apikey->key, $apikey->key, env('API_KEY_THRESHOLD'));
            }
            $app_id = $apikey['id'];
            $api = $request->route()->getName();
            // $host = $request->getClientIp();
            $host = $request->server('SERVER_ADDR');
            $url = $request->url();
            $params = $request->all();
            $success = 1;
            $error = '无';
            self::apikeyLog($app_id, $api, $host, $url, $params, $success, $error);
        }

        return $response;
    }

    /**
     * 将请求写入日志
     */
    public function apikeyLog($app_id, $api, $host, $url, $params, $success, $error)
    {
        $log = new ApiKeyRequestLog;
        $log->app_id = $app_id;
        $log->api = $api;
        $log->host = $host;
        $log->url = $url;
        $log->params = json_encode($params);
        $log->success = $success;
        $log->error = $error;
        $log->save();
    }
}
